from flask import Blueprint, render_template, request, redirect, url_for, flash, session
from pymongo import MongoClient

users_bp = Blueprint('users', __name__)

# MongoDB connection
client = MongoClient('mongodb://localhost:27017/')
db = client['scpy']
users_collection = db['users']

@users_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = users_collection.find_one({'username': username, 'password': password})
        if user:
            session['user'] = {
                'username': user['username'],
                'is_authenticated': True
            }
            flash('登录成功！', 'success')
            return redirect(url_for('home.index'))
        else:
            flash('用户名或密码错误！', 'danger')
    return render_template('frontend/login.html')

@users_bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        confirm_password = request.form['confirm_password']
        if password != confirm_password:
            flash('两次输入的密码不一致！', 'danger')
        else:
            if users_collection.find_one({'username': username}):
                flash('用户名已存在！', 'danger')
            else:
                users_collection.insert_one({'username': username, 'password': password})
                flash(f'注册成功！欢迎加入少儿编程，{username}！请使用您的账号密码登录。', 'success')
                return redirect(url_for('users.login'))
    return render_template('frontend/register.html')

@users_bp.route('/logout')
def logout():
    session.clear()
    flash('您已成功退出登录！', 'info')
    return redirect(url_for('home.index'))

@users_bp.route('/profile', methods=['GET', 'POST'])
def profile():
    if not session.get('user'):
        flash('请先登录！', 'warning')
        return redirect(url_for('users.login'))
        
    if request.method == 'POST':
        email = request.form.get('email')
        grade = request.form.get('grade')
        
        # 更新用户信息
        users_collection.update_one(
            {'username': session['user']['username']},
            {'$set': {'email': email, 'grade': grade}}
        )
        flash('个人信息更新成功！', 'success')
        return redirect(url_for('users.profile'))
    
    # 获取用户信息
    user_info = users_collection.find_one({'username': session['user']['username']})
    return render_template('frontend/profile.html',
                         email=user_info.get('email', ''),
                         grade=user_info.get('grade', ''))
